package com.gla.giliair.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gla.giliair.dao.AdminDao;
import com.gla.giliair.entity.*;
import com.gla.giliair.service.AdminService;
import com.gla.giliair.util.BeanUtil;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.web.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/24 10:28
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;

    @Override
    public Admin selectAdminById(Long adminId) {
        if (adminId != null) {
            AdminExample adminExample = new AdminExample();
            adminExample.or().andAdminIdEqualTo(adminId);
            List<Admin> adminList = adminDao.selectByExample(adminExample);
            if (adminList.isEmpty()) {
                return null;
            }
            return adminList.get(0);
        }
        return null;
    }

    @Override
    public List<Admin> selectAllAdmins(AdminExample orderBy) {
        List<Admin> adminList = adminDao.selectByExample(orderBy);
        return adminList;
    }

    @Override
    public List<Admin> selectAdminsByParams(AdminExample orderBy, AdminVO searchParams) {
        AdminExample.Criteria criteria = orderBy.createCriteria();
        if (StringUtils.hasText(searchParams.getUsername())) {
            criteria.andUsernameLike("%" + searchParams.getUsername() + "%");
        }
        List<Admin> adminList = adminDao.selectByExample(orderBy);
        return adminList;
    }

    @Override
    public Map<String, Object> findAllAdmins(String sort, boolean isASC, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Admin> adminList = selectAllAdmins(adminSort(sort, isASC));
        PageInfo pageInfo = new PageInfo(adminList);
        System.out.println(pageInfo);
        if (!adminList.isEmpty()) {
            List<AdminVO> adminVOList = BeanUtil.copyList(adminList, AdminVO.class);
            pageInfo.setList(adminVOList);
            return MapGenerator.getResWithData(200, "查询管理员列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "查询结果为空！");
        }
    }

    @Override
    public Map<String, Object> addAdmin(Admin admin) {
        AdminExample adminExample = new AdminExample();
        adminExample.or().andUsernameEqualTo(admin.getUsername());
        List<Admin> adminList = adminDao.selectByExample(adminExample);
        if (!adminList.isEmpty()) {
            return MapGenerator.getRes(503, "登录用户名已被占用！");
        }

        //填充创建、更新日期
        Date nowDate = new Date();
        admin.setCreateTime(nowDate);
        admin.setUpdateTime(nowDate);
        if (adminDao.insertSelective(admin) > 0) {
            return MapGenerator.getRes(200, "添加管理员成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> modifyAdmin(Admin admin) {
        Admin adminFromDB = selectAdminById(admin.getAdminId());
        if (adminFromDB == null) {
            return MapGenerator.getRes(503, "管理员不存在！");
        }

        if (StringUtils.hasText(admin.getUsername())) {
            AdminExample adminExample = new AdminExample();
            adminExample.or().andUsernameEqualTo(admin.getUsername());
            List<Admin> adminList = adminDao.selectByExample(adminExample);
            if (!adminList.isEmpty()) {
                return MapGenerator.getRes(504, "登录用户名已被占用，不能修改！");
            }
        }

        //把参数信息项中的非空字段合并到来自数据库的信息项中
        BeanUtil.copyOneIgnoreNull(admin, adminFromDB);
        //覆盖更新日期
        adminFromDB.setUpdateTime(null);
        if (adminDao.updateByPrimaryKeySelective(adminFromDB) > 0) {
            return MapGenerator.getRes(200, "修改管理员信息成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> deleteAdmin(Long adminId) {
        Admin adminFromDB = selectAdminById(adminId);
        if (adminFromDB == null) {
            return MapGenerator.getRes(501, "管理员不存在！");
        }
        if (adminDao.deleteByPrimaryKey(adminId) > 0) {
            return MapGenerator.getRes(200, "删除管理员成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> checkLogin(String username, String password, HttpSession httpSession) {
        AdminExample adminExample = new AdminExample();
        adminExample.or().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<Admin> adminList = adminDao.selectByExample(adminExample);

        if (!adminList.isEmpty() && httpSession != null) {
            Admin user = adminList.get(0);
            if (user.getIsLocked() == 1) {
                return MapGenerator.getRes(502, "该管理员已被封禁！");
            }
            AdminVO userVO = new AdminVO();
            BeanUtil.copyOne(user, userVO);

            httpSession.setAttribute("admin", userVO);
            System.out.println("登录管理员:" + httpSession);
            return MapGenerator.getResWithData(200, "登录成功！", userVO);
        }
        return MapGenerator.getRes(500, "用户名或密码错误！");
    }

    @Override
    public Map<String, Object> searchAdmins(String sort, boolean isASC, Integer page, Integer pageSize, AdminVO searchParams) {
        if (searchParams == null) {
            return MapGenerator.getRes(500, "搜索参数为空！");
        }
        PageHelper.startPage(page, pageSize);
        List<Admin> adminList = selectAdminsByParams(adminSort(sort, isASC), searchParams);
        PageInfo pageInfo = new PageInfo(adminList);
        if (!adminList.isEmpty()) {
            List<AdminVO> adminVOList = BeanUtil.copyList(adminList, AdminVO.class);
            pageInfo.setList(adminVOList);
            return MapGenerator.getResWithData(200, "查询管理员列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "查询结果为空！");
        }
    }

    //排序参数转化
    private AdminExample adminSort(String sort, boolean isASC) {
        AdminExample adminExample = new AdminExample();
        sort = sort == null ? "" : sort;
        String column = "";
        String order = "desc";
        if (isASC) {
            order = "asc";
        }
        switch (sort) {
            case "adminId":
                column = "admin_id";
                break;
            case "username":
                column = "username";
                break;
            case "password":
                column = "password";
                break;
            case "nickname":
                column = "nickname";
                break;
            case "role":
                column = "role";
                break;
            case "createTime":
                column = "create_time";
                break;
            case "updateTime":
                column = "update_time";
                break;
            case "isLocked":
                column = "is_locked";
                break;
            default:
        }
        if ("".equals(column)) {
            adminExample.setOrderByClause("admin_id desc");
        } else {
            if ("admin_id".equals(column)) {
                adminExample.setOrderByClause(String.format("%s %s", column, order));
            } else {
                adminExample.setOrderByClause(String.format("%s %s , admin_id desc", column, order));
            }
        }
        return adminExample;
    }
}
